﻿using System;
using System.Linq;
using System.Web;
using MarsExplorerWebSite.Model;

namespace MarsExplorerWebSite.Functions
{
    public class AddPlayerToTeam : FunctionBase
    {
        private MarsExplorerEntities dbContext;
        public string IPadId { get; set; }
        public string name { get; set; }
        public int TeamID { get; set; }
        public int PlayerType { get; set; }
        public AddPlayerToTeam(HttpContext context) : base(context)
        {
            InitializeProperties();
        }

        public override string Execute()
        {
            Player player = (from x in dbContext.Players where x.IPadID == IPadId select x).FirstOrDefault(); 

            if (player == null)
            {
                player = new Player { Name = name, IPadID = IPadId };
                dbContext.Players.AddObject(player);  
                dbContext.SaveChanges();
            }


            PlayersTeam pt = (from x in dbContext.PlayersTeams where x.TeamID == TeamID && x.PlayerTypeID == PlayerType select x).FirstOrDefault();
            if (pt == null)
            {
                pt = (from x in dbContext.PlayersTeams where x.PlayerID==player.PlayerID select x).FirstOrDefault();
                if (pt !=null)
                {
                    dbContext.PlayersTeams.DeleteObject(pt);
                    dbContext.SaveChanges();
                }
                pt = new PlayersTeam { PlayerID = player.PlayerID, TeamID = TeamID, PlayerTypeID = PlayerType };
                dbContext.PlayersTeams.AddObject(pt);
                dbContext.SaveChanges();
                return "OK";
            }
            else
            {
                return "NOTOK";
            }
          
           
        }

        public override void InitializeProperties()
        {
            

            try
            {
                IPadId = Parameters["ipadid"];
                name = Parameters["name"];
                TeamID = Convert.ToInt32(Parameters["teamid"]);
                PlayerType = Convert.ToInt32(Parameters["playertype"]);
                dbContext = new MarsExplorerEntities();
            }
            catch (Exception e)
            {
                string message = "";
                #if DEBUG
                message += " : " + e.ToString();
                #endif
            }
        }
    }
}